import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../generated/l10n/app_localizations.dart';

class LanguageService extends ChangeNotifier {
  static const String _languageKey = 'app_language';
  final SharedPreferences _prefs;

  // 当前语言
  Locale _currentLocale;

  // 支持的语言
  static const List<Locale> supportedLocales = [
    Locale('zh'), // 简体中文
    Locale('en'), // 英语
    Locale('es'), // 西班牙语
    Locale('ja'), // 日语
    Locale('ko'), // 韩语
    Locale('fr'), // 法语
    Locale('de'), // 德语
  ];

  LanguageService(this._prefs) : _currentLocale = const Locale('zh') {
    // 从本地存储加载语言设置
    final savedLanguage = _prefs.getString(_languageKey);
    if (savedLanguage != null) {
      _currentLocale = Locale(savedLanguage);
    }
  }

  // 获取当前语言区域
  Locale get currentLocale => _currentLocale;

  // 切换语言
  Future<void> setLocale(Locale locale) async {
    if (_currentLocale != locale && supportedLocales.contains(locale)) {
      _currentLocale = locale;
      await _prefs.setString(_languageKey, locale.languageCode);
      notifyListeners();
    }
  }

  // 获取语言名称
  String getLanguageName(BuildContext context, Locale locale) {
    final l10n = AppLocalizations.of(context)!;
    switch (locale.languageCode) {
      case 'zh':
        return l10n.simplifiedChinese;
      case 'en':
        return l10n.english;
      case 'es':
        return l10n.spanish;
      case 'ja':
        return l10n.japanese;
      case 'ko':
        return l10n.korean;
      case 'fr':
        return l10n.french;
      case 'de':
        return l10n.german;
      default:
        return l10n.english;
    }
  }
}
